package com.chpro.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 14-7-13.
 */
public class ImanageUtil {
    /**
     * 图片转二进制
     * @param fileStr
     * @return
     * @throws Exception
     */
    public static String imageToByte(String fileStr)throws Exception{
        BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        File f = new File(fileStr);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 二进制转图片
     * @param str 字符
     * @param fileStr 保存文件路径
     * @throws Exception
     */
    public static void byteToImage(String str,String fileStr)throws Exception{
        BASE64Decoder decoder=new BASE64Decoder();
        byte[] bytes=decoder.decodeBuffer(str);
        File file=new File(fileStr);
        FileOutputStream fos=new FileOutputStream(file);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }
}
